package com.lvmama.rhino.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lvmama.rhino.base.CookieUtil;
import com.lvmama.rhino.base.HttpClientUtil;
import com.lvmama.rhino.utils.RhinoConstant;

import redis.clients.jedis.Jedis;

public class SessionInterceptor implements HandlerInterceptor{
	

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		String token = request.getParameter("token");
		RhinoConstant rhinoConstant = RhinoConstant.getInstance();
		String ssoServiceUrl = rhinoConstant.getValue("ssoServiceUrl");
		String tokenValidateUrl = rhinoConstant.getValue("tokenValidateUrl");
		if(null == token) {
			Cookie cookie = CookieUtil.getCookieByName(request, "token");
			if(null != cookie) {
				token = cookie.getValue();
			}
		}
		
		if(null == token) {
			//没有token，重定向至sso server登录页
			response.sendRedirect(ssoServiceUrl);
			return false;
				
		}else {
			String urlString = request.getRequestURI();
			if(urlString.endsWith("/logout")) {
				String JedisUrl = rhinoConstant.getValue("JedisUrl");
				String JedisPort = rhinoConstant.getValue("JedisPort");
				String JedisPassword = rhinoConstant.getValue("JedisPassword");
				Jedis jedis = new Jedis(JedisUrl, Integer.parseInt(JedisPort));
				jedis.auth(JedisPassword);
		    	jedis.del(token.getBytes());
		    	jedis.close();
		    	response.sendRedirect(ssoServiceUrl);//沿着古失败，重定向至sso server登录页
				return false;
			}

			//有token,去sso server验证token的有效性
			Map<String, String> map = new HashMap<String, String>();
			map.put("token", token);
			String result = HttpClientUtil.doGet(tokenValidateUrl, map);
			if(StringUtils.isNotBlank(result)){//验证成功，跳转至首页，并从redis中获取权限
				Cookie cookie = new Cookie("token", token);
				cookie.setPath("/");
				response.addCookie(cookie);
				return true;
			} else
				response.sendRedirect(ssoServiceUrl);//沿着古失败，重定向至sso server登录页
				return false;
			
		}
	}

}
